package com.mrx.commons.trace;

import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr.X
 * @since 2024-04-11 09:30
 **/
@Component
public class CORSFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(
            @NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
            @NotNull FilterChain filterChain
    ) throws ServletException, IOException {
        // 设置允许跨域的源
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 设置允许的HTTP方法
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        // 设置允许的请求头
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type, x-token");
        // 对于预检请求(OPTIONS)直接返回
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        // 继续执行后续的过滤器或者Servlet
        filterChain.doFilter(request, response);
    }
}
